# -*- coding: utf-8 -*-
import os, time, sys
from make_and_upload_report.uploadfile import UploadFileByHttp
import cgi
import shutil
import re
try: 
  import xml.etree.cElementTree as ET
except ImportError: 
  import xml.etree.ElementTree as ET
from adb import ADB
from fileutils import clearDir
from fileutils import copytree
import getpass, platform

html1 = """<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>"""
html2 = """</title>
<style type="text/css">
body {
    font:normal 80% verdana,arial,helvetica;
    color:#000000;
}
table tr td, table tr th {
    font-size: 68%;
}
table.details tr th{
    font-weight: bold;
    text-align:left;
    background:#a6caf0;
}
table.details tr td{
    background:#eeeee0;
}

table.general tr th{
    font-weight: bold;
    text-align:left;
    background:#a6caf0;
}
table.general tr td{
    background:#eeeee0;
}

p {
    line-height:1.5em;
    margin-top:0.5em; margin-bottom:1.0em;
}
h1 {
    margin: 0px 0px 5px; font: 250% verdana,arial,helvetica; text-align:center;
}
h2 {
    margin-top: 1em; margin-bottom: 0.5em; font: bold 125% verdana,arial,helvetica; text-align:center;
}
h3 {
    margin-bottom: 0.5em; font: bold 115% verdana,arial,helvetica
}
h4 {
    margin-bottom: 0.5em; font: bold 100% verdana,arial,helvetica
}
h5 {
    margin-bottom: 0.5em; font: bold 100% verdana,arial,helvetica
}
h6 {
    margin-bottom: 0.5em; font: bold 100% verdana,arial,helvetica
}
.error {
    font-weight:bold; color:red;
}
.fail {
    font-weight:bold; color:purple;
}
.pass {
    color:black;
}
.Properties {
  text-align:right;
}

</style></head>
<body>
<a href=\""""
html3 = """\">查看测试详情</a>
<h1>SDET Test Report For 
"""
html4 = """</h1>"""
html5 = """<div style="text-indent:3em">
<br/><br/>
测试说明：
<div>UIA：基于uiautomator开发的APP层自动化测试用例。</div>
<div>SMOKE：基于framework API实现的基本功能冒烟测试。</div>
<div>BVT：基于framework API实现的入口用例，覆盖的功能点相比较SMOKE更加细致。</div>
<div>AppStart：基于monkey实现，对应用实现快速的启动，判别应用启动是否正常。</div>
</div>
</body>
</html>"""

def cur_file_dir():
     #获取脚本路径
     path = sys.path[0]
     #判断为脚本文件还是py2exe编译后的文件，如果是脚本文件，则返回的是脚本的目录，如果是py2exe编译后的文件，则返回的是编译后的文件路径
     if os.path.isdir(path):
         return path
     elif os.path.isfile(path):
         return os.path.dirname(path)
         
def calStatistics(xmlFile):
    tree = ET.parse(xmlFile)     #打开xml文档 
    root = tree.getroot()
    ret = {"Total":0, "Failed":0, "Error":0, "Passed": 0, "Time":0.0}
    userSuiteTime = False
    try:#如果有Suite有time属性, 则使用Suite的time属性
        ret["Time"] = float(root.get('time'))
        userSuiteTime = True
    except:
        pass
    for case in root.iter('testcase'): #找到root节点下的所有testcase节点
        if case.find('failure') is not None:   #子节点下节点failure的值 
            ret["Failed"] += 1
        elif case.find('error') is not None:   #子节点下节点failure的值 
            ret["Error"] += 1
        else:
            ret["Passed"] += 1
        ret["Total"] += 1
        if not userSuiteTime:
            try:
                ret["Time"] += float(case.get('time'))
            except:
                pass
    return ret
    
def calCTSStatistics(xmlFile, androidVersion):
    import re  
    def multiple_replace(text,adict):  
        rx = re.compile('|'.join(map(re.escape,adict)))  
        def one_xlat(match):  
            return adict[match.group(0)]  
        return rx.sub(one_xlat,text) #每遇到一次匹配就会调用回调函数  
      
    def strptimeCTS(timeStr):
        adic1 = {"星期日":"Sun","星期一":"Mon","星期二":"Tue","星期三":"Wed","星期四":"Thu","星期五":"Fri","星期六":"Sat"}
        adic2 = {"一月":"Jan","二月":"Feb","三月":"Mar","四月":"Apr","五月":"May","六月":"Jun","七月":"Jul","八月":"Aug","九月":"Sep","十月":"Oct","十一月":"Nov","十二月":"Dec"}
        timeStr = multiple_replace(timeStr, adic1)
        timeStr = multiple_replace(timeStr, adic2)
        return time.strptime(timeStr, '%a %b %d %H:%M:%S CST %Y')
    tree = ET.parse(xmlFile)     #打开xml文档 
    root = tree.getroot()
    ret = {"Total":0, "Failed":0, "Error":0, "Passed": 0, "Time":0.0}
    userSuiteTime = False
    try:#如果有Suite有time属性, 则使用Suite的time属性
        start = root.get('starttime')
        end = root.get('endtime')
        start =  strptimeCTS(start.encode("UTF-8"))
        end =  strptimeCTS(end.encode("UTF-8"))
        ret["Time"] = time.mktime(end) - time.mktime(start)
        userSuiteTime = True
    except:
        pass
        
    summary = root.find("Summary")
    ret["Failed"] = int(summary.get("failed"))
    if not androidVersion or androidVersion != '7':
        ret["Error"] = int(summary.get("notExecuted"))
    else:
        ret["Error"] = int(summary.get("not_executed"))
    ret["Passed"] = int(summary.get("pass"))
    ret["Total"] = ret["Failed"] + ret["Error"] + ret["Passed"]
    return ret

def generalNVCmpStatistics(htmlFile, reportUrl):
    tree = ET.parse("NV Compare/report/report.xml")     #打开xml文档 
    root = tree.getroot()
    oldQcn = root.find("oldQcn")
    newQcn = root.find("newQcn")
    statE = root.find('statistic')
    head=["Test Type", "QCN"]
    line=["NV Compare", "old: " + os.path.basename(oldQcn.text) + "<br/>new: " + newQcn.text]
    for s in statE: #找到root节点下的所有testcase节点
        head.append(s.tag+"(" + s.get("Result")+")")
        line.append(s.text)
    
    head.append("Detail")
    line.append("<a href=\""+ reportUrl +"\">Click to Detail</a>")
    htmlFile.write("<div><br/></div>\n")
    htmlFile.write("<h2>NV Compare Statistics</h2>\n")
    htmlFile.write("<table class=\"general\" border=\"0\" cellpadding=\"5\" cellspacing=\"2\" width=\"95%\">\n")
    htmlFile.write("<tr><th>"+"</th><th>".join(head)+"</th></tr>\n")
    htmlFile.write("<tr><td>"+"</td><td>".join(line)+"</td></tr>\n</table>\n")

def readDeviceInfo():
    adbPath = None#"D:\\android-sdk-windows\\platform-tools\\adb.exe"
    deviceID = os.getenv('DEVICE_ID')
    if not deviceID:
        deviceID = None    #设备ID, 如果是None则不判断ID
    timeout = 3
    adb = ADB(adbPath)
    devices = adb.listDevices()
    if deviceID:
        if not deviceID in devices:
            raise Exception("Cannot find device " + deviceID)
    else:
        if len(devices)==0:
            raise Exception("No device connect!")
        if len(devices)>1:
            raise Exception("More than one devices connect: " + str(devices) + ". Must special one!")
    info = adb.shell("getprop", deviceID)[1].split('\n')
    def getInfo(info, id):
        try:
            for l in info:
                if id not in l:
                    continue
                index = l.find(':')
                if index != -1:
                    l =l[index+2:]
                    l = l.strip()
                    l = l[1:-1]
                    return l
        except:
            return None
        return None
        
    imei = getInfo(info, "persist.build.imei")
    buildDate = getInfo(info, "ro.build.date")
    fingerprint = getInfo(info, "ro.build.fingerprint")
    innerVersion = getInfo(info, "ro.build.inner.version")
    buildType = 	getInfo(info, "ro.build.type")
    androidVersion =	getInfo(info, "ro.build.version.release")
    hardware = getInfo(info, "ro.hardware")
    productName = getInfo(info, "ro.product.name")
    model = getInfo(info, "ro.product.model")
    serialNo = getInfo(info, "ro.serialno")
    board = getInfo(info, "ro.product.board")
    brand = getInfo(info, "ro.product.brand")

    return {"imei":str(imei), 'buildDate':str(buildDate), 'fingerprint': str(fingerprint), 'innerVersion':str(innerVersion),\
    "buildType":str(buildType), 'androidVersion':str(androidVersion), "hardware":str(hardware), 'productName':str(productName),\
    "model":str(model), 'serialNo':str(serialNo),"board":str(board), 'brand':str(brand)}
    
def writeDeviceInfoToHtml(info, tStatistics):
    tStatistics.write("<table class=\"general\" border=\"0\" cellpadding=\"5\" cellspacing=\"2\" width=\"95%\">\n")
    tStatistics.write("<tr><th colspan=4>Device Information</th></tr>\n")
    tStatistics.write("<tr><td>IMEI</td><td>%s</td><td>BUILD_DATE</td><td>%s</td></tr>\n" % (str(info['imei']), str(info['buildDate'])))
    tStatistics.write("<tr><td>Fingerprint</td><td>%s</td><td>inner Version</td><td>%s</td></tr>\n" % (str(info['fingerprint']), str(info['innerVersion'])))
    tStatistics.write("<tr><td>Hardware</td><td>%s</td><td>Product Name</td><td>%s</td></tr>\n" % (str(info['hardware']), str(info['productName'])))
    tStatistics.write("<tr><td>Model</td><td>%s</td><td>Serial No</td><td>%s</td></tr>\n" % (str(info['model']), str(info['serialNo'])))
    tStatistics.write("<tr><td>Board</td><td>%s</td><td>Brand</td><td>%s</td></tr>\n" % (str(info['board']), str(info['brand'])))
    tStatistics.write("<tr><td>Build Type</td><td>%s</td><td>Android Version</td><td>%s</td></tr>\n" % (str(info['buildType']), str(info['androidVersion'])))
    tStatistics.write("</table>\n")
    
def writeHostInfoToHtml(tStatistics):
    tStatistics.write("<div></br></div><table class=\"general\" border=\"0\" cellpadding=\"5\" cellspacing=\"2\" width=\"95%\">\n")
    tStatistics.write("<tr><th>Host Information</th></tr>\n")
    hostInfo = getpass.getuser() + "@" + platform.node() + "(" +platform.platform()+")"
    tStatistics.write("<tr><td>"+hostInfo+"</td></tr>\n")
    tStatistics.write("</table>\n")
	
def getTestMailReceivers(testTypes):
    mailTo = ""
    mailCC = ""
    for t in testTypes:
        try:
            mailInfo = os.path.join(t, "report", "mail.txt")
            if os.path.exists(mailInfo):
                for line in open(os.path.join(cur_file_dir(), "mail.txt")).readlines():
                    a,b = line.split(":")
                    if a.strip().upper() == "TO":
                        mailTo += b.strip().strip(";") + ";"
                    if a.strip().upper() == "CC":
                        mailCC += b.strip().strip(";") + ";"
        except:
            continue
    return mailTo, mailCC
    
def fromatTime(seconds):
    try:
        seconds = int(seconds)
    except:
        return seconds
    if seconds>=3600:
        return str(seconds/3600)+"h "+str(seconds%3600/60)+"min "+str(seconds%3600%60)+"s"
    elif seconds>=60:
        return str(seconds/60)+"min "+str(seconds%60)+"s"
    else:
        return str(seconds) + "s"
    
if __name__ == '__main__':
    productName = os.getenv('PRODUCT_NAME')
    mailRecipients = os.getenv('REPORT_RECIPIENTS')
    testTypesStr = os.getenv('TEST_STAGES')
    reportDir = os.path.abspath("testdata/report")
    reportUrl = os.getenv('BUILD_URL')+"TestReport/"
    if not os.path.exists(reportDir):
        os.makedirs(reportDir)
    try:
        clearDir("testdata/report", ["stylesheet.css"])
    except WindowsError, e:
        print 'except:', e
    testTypes = []
    for t in re.split("\r\n|\n",testTypesStr):
        if t and t not in ["Download Version","Flash Version","Boot Wizard", "Send Report"]:
            testTypes.append(t)
    
    tStatistics = open(os.path.join(reportDir,"summary.html"), 'w')
    tStatistics.write(html1)
    tStatistics.write(productName + "测试报告")
    tStatistics.write(html2)
    tStatistics.write(reportUrl)
    tStatistics.write(html3)
    tStatistics.write(productName)
    tStatistics.write(html4)
    try:
        info = readDeviceInfo()
        writeDeviceInfoToHtml(info, tStatistics)
        writeHostInfoToHtml(tStatistics)
    except Exception, e:
        print(str(e))
    tStatistics.write("<div><br/></div><h2>Test Statistics</h2>\n")
    tStatistics.write("<table class=\"general\" border=\"0\" cellpadding=\"5\" cellspacing=\"2\" width=\"95%\">\n")
    tStatistics.write("<tr><th width=\"40%\">Test Type</th><th>Passed</th><th>Failed</th><th>NotExecuted</th><th>Total</th><th>Times</th><th>Detail</th></tr>\n")
    for t in testTypes:
        if t in ['NV Compare',]:
            continue
        treportDir = os.path.abspath(t+"/report")
        reportFile = os.path.join(treportDir, "report.html")
        if os.path.exists(reportFile):
            try:
                copytree(t +'/report', "testdata/report")
                #os.system('cp -rf ' + t +'/report/* ' + "testdata/report")
                os.system('''mv -f testdata/report/report.html testdata/report/\"''' + t + '.html\"')
            except Exception, e:
                print("warning: "+str(e))
        else:
            print("warning: cannot find " + reportFile)
        reportFile = os.path.join(treportDir, "report.xml")
        if os.path.exists(reportFile):
            stat = calStatistics(reportFile)
            tStatistics.write("<tr><td>%s</td><td>%d</td><td>%d</td><td>%d</td><td>%d</td><td>%s</td><td><a href=\"%s\">Click to Detail</a></td></tr>\n" % (t, stat["Passed"], stat["Failed"], stat["Error"], stat["Total"], fromatTime(stat["Time"]), reportUrl))
        else:
            androidVersion = os.getenv('ANDROID_VERSION')
            print("ANDROID_VERSION is " + str(androidVersion))
            if not androidVersion or androidVersion != '7':
                reportFile2 = os.path.join(treportDir, "testResult.xml")#CTS6报告
            else:
                print("ANDROID_VERSION is " + androidVersion)
                reportFile2 = os.path.join(treportDir, "test_result.xml")#CTS6报告
            if os.path.exists(reportFile2):
                stat = calCTSStatistics(reportFile2, androidVersion)
                tStatistics.write("<tr><td>%s</td><td>%d</td><td>%d</td><td>%d</td><td>%d</td><td>%s</td><td><a href=\"%s\">Click to Detail</a></td></tr>\n" % (t, stat["Passed"], stat["Failed"], stat["Error"], stat["Total"], fromatTime(stat["Time"]), reportUrl))
            else:
                print("warning: cannot find " + reportFile + " or " + reportFile2)
    tStatistics.write("</table>\n")
    
    if "NV Compare" in testTypes:
        generalNVCmpStatistics(tStatistics, reportUrl)
        shutil.copy("NV Compare/report/report.html", os.path.join(reportDir, "NV Compare.html"))
    tStatistics.write(html5)
    tStatistics.close()

    mailTo, mailCC = getTestMailReceivers(testTypes)
    for line in re.split("\r\n|\n",mailRecipients):
        try:
            a,b = line.split(":")
        except:
            continue
        if a.strip().upper() == "TO":
            mailTo = b.strip()
        if a.strip().upper() == "CC":
            mailCC = b.strip()
    print "Mailcc: ", mailCC
    print "MailTo: ", mailTo
    currentTime=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time()))
    subject = "【"+productName +"】"+currentTime+"构建版本测试报告"
    upload = UploadFileByHttp(productName, reportDir, subject, mailTo, mailCC, "summary.html")
    upload.uploadfile()
    print upload.get_upload_result()
